package com.example.googlemapdrawroutelast;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import com.example.googlemapdrawroutelast.task.DropRouteTask;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.LinearGradient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.Toast;

public class ListOfRoutesActivity extends ListActivity implements
		OnClickListener, AsyncResponseListView {

	List<RouteInfo> routes;
	RouteAdapter adapter;
	int userId;
	private ArrayAdapter<String> la;
	RouteInfo routeInfo;
	ApplicationData appData;
	ContextMenu contextMenu;
	RouteData routeData;
	View v;
	// GetRouteByIdTask getRouteTask = new GetRouteByIdTask(routeData);
	GetRouteByIdTask GetRouteTask = new GetRouteByIdTask(routeInfo);

	// Button
	Button showRouteButton;
	Button closePopupButton;
	//
	PopupWindow pwindo;
	Boolean bMenuCancelled = false;
	// Edit route Details
	RouteEditDetails routeEditDetails;
	// is visible or is not visible Edit option
	Boolean isVisible = false;
	//progress bar
	private ProgressBar progressBar;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list_of_routes);

		Bundle extras = getIntent().getExtras();

		this.routeInfo = new RouteInfo();
		this.appData = new ApplicationData();

		this.routeData = new RouteData();
		GetRouteTask.delegate = this;

		if (extras != null) {
			int idUser = extras.getInt("idUser");
			if (idUser != 0) {
				this.appData.setIdUser(idUser);
			}
		}

		routes = getIntent().getParcelableArrayListExtra("routes");
		// userId = getIntent().getExtras().getInt("idUser");
		// userId = 53;
		
		progressBar = (ProgressBar) findViewById(R.id.progressBar1);
				
		/*
		 * long time1= System.currentTimeMillis();
		 * android.util.Log.i("Time Class ListOfRoutes",
		 * " Time 2value in millisecinds "+time1);
		 */
		adapter = new RouteAdapter(getBaseContext(), routes, appData);
		setListAdapter(adapter);

		/*
		 * long time2= System.currentTimeMillis();
		 * android.util.Log.i("Time Class ListOfRoutes",
		 * " Time 2value in millisecinds "+time2); long timeEnd = time2 - time1;
		 * android.util.Log.i("Time Class ", " roznica "+ timeEnd);
		 */
		// getRouteTask.delegate = this;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		getMenuInflater().inflate(R.menu.list_of_routes, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.myroutes:
			isVisible = true;
			adapter.filter(this.appData.getIdUser());
			registerForContextMenu(getListView());

			// getListView().setAdapter();
			return true;
		case R.id.allroutes:
			isVisible = false;
			adapter.displayAll();
			unregisterForContextMenu(getListView());
			return true;
		}
		return false;
	}

	// delete show
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.context_menu, menu);
		this.contextMenu = menu;

	}

	// klikanie na poszczzegolne item w ListView
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {

		// int routeId = routes.get(position).getId();
		int routeId = adapter.getItem(position).getId();
		// new GetRouteByIdTask().execute(routeId);
		String desc;

		if (GetRouteTask.getStatus() == AsyncTask.Status.FINISHED) {
			GetRouteTask = new GetRouteByIdTask(routeInfo);
			GetRouteTask.execute(routeId);
		}

		if (GetRouteTask.getStatus() != AsyncTask.Status.RUNNING) {
			GetRouteTask.execute(routeId);
		}

	}

	public void AlertDialogInfoRoute(String description, String name,
			int id_route) {

		AlertDialog.Builder builder = new AlertDialog.Builder(
				ListOfRoutesActivity.this);
		builder.setTitle(name);
		builder.setMessage(description);

		builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				// Do something
				// getApplicationContext()
				Intent intent = new Intent(getApplicationContext(),
						MainActivity.class);
				intent.putExtra("route", routeInfo);
				intent.putExtra("isRouteDrawing", false);
				// intent.putExtra("route",routeInfo);
				startActivityForResult(intent, 0);

			}
		});

		/*
		 * builder.setNeutralButton("Edit", new
		 * DialogInterface.OnClickListener() { public void
		 * onClick(DialogInterface dialog, int id) { // User cancelled the
		 * dialog
		 * 
		 * AlertDialogEditRouteInfo(,name); } });
		 */

		if (isVisible) {
			// My own oncLickListenerwithDialogInterface
			builder.setNeutralButton("Edit",
					new MyOnClickListenerDialogInterface(name, description,
							id_route) {

					});
		}
		//
		// przetestuj to !!!;)

		builder.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// User cancelled the dialog

					}
				});

		builder.show();
	}

	private class MyOnClickListenerDialogInterface implements
			DialogInterface.OnClickListener {

		private String name;
		private String desc;
		private int route_id;

		public MyOnClickListenerDialogInterface(String name, String desc,
				int route_id) {
			super();
			this.name = name;
			this.desc = desc;
			this.route_id = route_id;
		}

		@Override
		public void onClick(DialogInterface dialog, int i) {
			// TODO Auto-generated method stub

			/*
			 * if(!isVisible){
			 * //((AlertDialog)dialog).getButton(i).setVisibility
			 * (View.INVISIBLE);
			 * 
			 * ((AlertDialog)dialog).getButton(i).setEnabled(false); }else{
			 */
			AlertDialogEditRouteInfo(name, desc, route_id);
			// }
		}

	}

	private class MyOnClickListenerDialogInterface2 implements
			DialogInterface.OnClickListener {

		private EditText titleBox;
		private EditText descriptionBox;
		private int id_route;

		public MyOnClickListenerDialogInterface2(EditText titleBox,
				EditText descriptionBox, int id_route) {
			super();
			this.titleBox = titleBox;
			this.descriptionBox = descriptionBox;
			this.id_route = id_route;
		}

		@Override
		public void onClick(DialogInterface dialog, int i) {
			// TODO Auto-generated method stub

			new ChangeDescriptionTask(titleBox.getText().toString(),
					descriptionBox.getText().toString()).execute(id_route);
			adapter.changeDescription(titleBox.getText().toString(),
					descriptionBox.getText().toString(), id_route);
			// new MenuActivity.GetRoutesTask().execute();
//			adapter.filter(appData.getIdUser());
//			registerForContextMenu(getListView());
//			adapter.notifyDataSetChanged();
		}

	}

	// Edit Alert Dialog!!!!!

	public void AlertDialogEditRouteInfo(String name, String desc,int route_id) {

		AlertDialog.Builder builder = new AlertDialog.Builder(
				ListOfRoutesActivity.this);
		// builder.setTitle(name);
		// builder.setMessage(description);

		// Context context = getContext();
		LinearLayout layout = new LinearLayout(ListOfRoutesActivity.this);
		layout.setOrientation(LinearLayout.VERTICAL);

		final EditText titleBox = new EditText(ListOfRoutesActivity.this);
		titleBox.setHint(name);
		layout.addView(titleBox);

		final EditText descriptionBox = new EditText(ListOfRoutesActivity.this);
		descriptionBox.setHint(desc);
		descriptionBox.setSelection(descriptionBox.getText().length());
		layout.addView(descriptionBox);

		builder.setView(layout);
		// niedziala pobieranie nazwy i opisu, w bazie zmienia na Null null
		// get new Details Route
		String newName = titleBox.getText().toString(); // tu nie dziala zwraca
														// NULL
		String newDescription = descriptionBox.getText().toString(); // tu nie
																		// dziala
																		// zwraca
																		// NULL

		/*
		 * final EditText editDescEditText = new
		 * EditText(ListOfRoutesActivity.this); LinearLayout.LayoutParams lp =
		 * new LinearLayout.LayoutParams(
		 * LinearLayout.LayoutParams.MATCH_PARENT,
		 * LinearLayout.LayoutParams.MATCH_PARENT);
		 * 
		 * editDescEditText.setLayoutParams(lp);
		 * builder.setView(editDescEditText); // uncomment this line
		 */
		/*
		 * final EditText editDescEditText2 = new
		 * EditText(ListOfRoutesActivity.this); LinearLayout.LayoutParams tr =
		 * new LinearLayout.LayoutParams(100, 100);
		 * editDescEditText2.setLayoutParams(tr);
		 * builder.setView(editDescEditText2); //
		 */
		routeEditDetails = new RouteEditDetails(newName, newDescription);

		builder.setPositiveButton("Ok", new MyOnClickListenerDialogInterface2(
				titleBox, descriptionBox, route_id) {

		});

		builder.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// User cancelled the dialog
					}
				});
		builder.show();
	}

	private class ChangeDescriptionTask extends
			AsyncTask<Integer, Void, Boolean> {

		// private RouteData routeData;
		private PopupWindow window;
		private String title;
		private String desc;

		/*
		 * public ChangeDescriptionTask(RouteData routeData, PopupWindow window)
		 * { super(); this.routeData = routeData; this.window = window; }
		 */

		public ChangeDescriptionTask(String title, String desc) {
			// TODO Auto-generated constructor stub
			this.title = title;
			this.desc = desc;
		}

		protected void onPreExecute() {
			super.onPreExecute();
			/*
			 * timings = new TimingLogger("TopicLogTag", "AddRouteTask");
			 */

		}

		@Override
		protected Boolean doInBackground(Integer... params) {

			try {

				// Debug.startMethodTracing("myapp2");

				String strUrl = "http://" + UrlClass.getUrl()
						+ "/v1/editRoute/" + params[0];

				URL url = null;

				url = new URL(strUrl);

				HttpURLConnection connection = (HttpURLConnection) url
						.openConnection();
				connection.setRequestMethod("PUT");
				connection.setDoOutput(true);
				OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
						connection.getOutputStream());

				outputStreamWriter.write("name_route=" + title
						+ "&description=" + desc);

				outputStreamWriter.flush();
				outputStreamWriter.close();

				InputStream iStream = connection.getInputStream();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(iStream));

				StringBuffer sb = new StringBuffer();
				String line = "";

				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}

				reader.close();
				iStream.close();

				String jsonResponseString = sb.toString();
				JSONObject jsonResponse = new JSONObject(jsonResponseString);

				// assign json responses to local strings
				// mysql
				// table
				boolean isAdded = !Boolean.parseBoolean(jsonResponse
						.getString("error"));

				// if (!isValidBool) {
				// String idRoute = jsonResponse.getString("name_route");
				// this.routeData.setIdRoute(idRoute);
				// }

				// Adding point to road
				// SavePointToDatabase(routeDetails.getCharacteristicPoints(),
				// routeData.getIdRoute());
				// Debug.stopMethodTracing();

				return isAdded;

			} catch (Exception e) {
				e.printStackTrace();
				// Display toast when there is a conncetion error
				Toast.makeText(getBaseContext(), "Connection Error Exception",
						Toast.LENGTH_SHORT).show();
			}
			return false;

		}

		@Override
		protected void onPostExecute(Boolean isRouteAdded) {
			super.onPostExecute(isRouteAdded);
			if (isRouteAdded) {

				// timings.dumpToLog();
				// this.window.dismiss(); //
				/*
				 * GetRouteByIdTask2 new GetRouteByIdTask2(view,
				 * getApplicationContext(), appData).execute(routeId, userId2);
				 */
				adapter.notifyDataSetChanged();
				Toast.makeText(getBaseContext(), "Route's details has changed",
						Toast.LENGTH_SHORT).show();
			}

		}

	}

	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();

		int index = info.position;
		View view = info.targetView;
		int id = (int) info.id;

		switch (item.getItemId()) {

		case R.id.menuDelete:
			RouteInfo routeToDelete = adapter.getItem(index);

			int routeId = routeToDelete.id_route;
			int userId2 = appData.getIdUser();

			new DropRouteTask(view, getApplicationContext()).execute(routeId,
					userId2);
			adapter.remove(index);

			return true;
		case R.id.menuCancel:

			bMenuCancelled = true;
			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}

	@Override
	public void onContextMenuClosed(Menu menu) {
		// TODO Auto-generated method stub
		super.onContextMenuClosed(menu);
		if (bMenuCancelled) {

		}
	}

	/*
	 * public void showNote(int id, View v) { int routeId =
	 * routes.get(id).getId(); new GetRouteByIdTask(v).execute(routeId); String
	 * desc = routeInfo.getDescription(); initiatePopupWindowRoute(desc); }
	 */

	private class GetRouteByIdTask extends AsyncTask<Integer, Void, RouteInfo> {

		private View view;
		public AsyncResponseListView delegate = null;

		// private RouteData rData = new RouteData();

		public GetRouteByIdTask(RouteInfo routeInfo) {
			// TODO Auto-generated constructor stub
		}
				/*
		 * public GetRouteByIdTask(RouteData rData) { super(); //this.rData =
		 * rData; }
		 */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();

			progressBar.setVisibility( ProgressBar.VISIBLE);
			//Toast.makeText(getBaseContext(), "Logowanie...", Toast.LENGTH_LONG).show();
			
		}
		@Override
		protected RouteInfo doInBackground(Integer... params) {
			try {
				String strUrl = "http://" + UrlClass.getUrl() + "/v1/route/"
						+ params[0].toString();
				URL url = new URL(strUrl);
				HttpURLConnection connection = (HttpURLConnection) url
						.openConnection();
				connection.setConnectTimeout(15000);
				connection.setReadTimeout(15000);
				connection.setRequestMethod("GET");
				connection.setDoOutput(true);

				InputStream iStream = connection.getInputStream();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(iStream));

				StringBuffer sb = new StringBuffer();
				String line = "";

				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}

				reader.close();
				iStream.close();

				String jsonResponseString = sb.toString();
				JSONObject jsonResponse = new JSONObject(jsonResponseString);
				routeInfo = new RouteInfo(jsonResponse.getInt("id_route"),
						jsonResponse.getString("name_route"),
						jsonResponse.getString("description"),
						jsonResponse.getString("coordinates"),
						jsonResponse.getString("characteristicPoints"),
						jsonResponse.getInt("id_user"));

				String descriptionRoute = routeInfo.getDescription();
				String nameRoute = routeInfo.getName();
				int idRoute = routeInfo.getId();
				// routeData.setDescription(description);
				routeData.setDescriptionRoute(descriptionRoute);
				routeData.setName(nameRoute);
				routeData.setIdRoute(idRoute);

				return routeInfo;

			} catch (Exception e) {
				e.getMessage();
			}
			return routeInfo;
		}

		protected void onPostExecute(RouteInfo result) {
			// super.onPostExecute(route);
			/*
			 * Intent intent = new Intent(view.getContext(),
			 * MainActivity.class); intent.putExtra("route",route);
			 */
			// startActivityForResult(intent, 0);

			/*
			 * routeInfo.getName(); String description
			 * =routeInfo.getDescription();
			 * 
			 * initiatePopupWindowRoute(description);
			 */
			// delegate.processFinish(result);

			// listener.onTaskCompleted(result);
			// result.getDescriptionRoute();
			// super.onPostExecute(result);

			String desc = routeData.getDescriptionRoute();
			String name = routeData.getName();
			int id_route = routeData.getIdRoute();
			AlertDialogInfoRoute(desc, name, id_route);
			progressBar.setVisibility( ProgressBar.INVISIBLE);
			// delegate.processFinish(result);

		}

	}

	@Override
	public void processFinish(RouteData output) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

	}

}